#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time
from signal import SIGTERM
from ddns_daemon import DdnsDaemon

pid_file = '/home/reciente/pyddns.pid'
log_file = '/home/reciente/log'
err_log_file = '/home/reciente/err_log'

def start():
  """
    Start pyddns daemon process.
  """
  daemon = DdnsDaemon(
    pid_file,
    stdout=log_file,
    stderr=err_log_file)
  daemon.start()

def stop():
  """
    Stop pyddns daemon process.
  """
  # Get the pid from the pidfile.
  try:
    pf = file(pid_file, 'r')
    pid = int(pf.read().strip())
    pf.close()
  except IOError:
    pid = None

  if not pid:
    message = "pidfile %s does not exists. Daemon not running?\n"
    sys.stderr.write(message % pid_file)
    return # not an error in a restart

  # Try killing the daemon process
  try:
    while 1:
      os.kill(pid, SIGTERM)
      time.sleep(1)
  except OSError, err:
    err = str(err)
    if err.find("No such process") > 0:
      if os.path.exists(pid_file):
        os.remove(pid_file)
      else:
        print str(err)
        sys.exit(1)
